package com.humh.makeplanning;


import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

// 物料科主任
public class MaterialsDepartmentDirector {

  // 物料工人集合
  private Set<MaterialWorker> materialWorkerSet;

  /**
   * @param materialWorkerNum 物料工人数量
   */
  public MaterialsDepartmentDirector(final int materialWorkerNum) {
    this.materialWorkerSet = new HashSet<>();

    for (int i = 0; i < materialWorkerNum; i++) {
      materialWorkerSet.add(new MaterialWorker());
    }
  }

  /**
   * 接受加工任务
   * @param taskNum
   * @param workshopId
   */
  public void acceptProcessingTasks(Long workshopId, int taskNum) {

    for(int i=0;i<taskNum;i++){
      Task task = new Task(workshopId,createTaskId());
      assignTasks(task);
    }
  }

  /**
   * 获取任务时间，即最晚完成任务人的结束时间
   */
  public LocalDateTime getTheTaskTime(){
    MaterialWorker availablePeopleToAssignTasks = findAvailablePeopleToAssignTasks(false);
    return availablePeopleToAssignTasks.getTheLastTimeToComplete();
  }

  /**
   * 分配任务
   */
  private void assignTasks(Task task) {
    //TODO 可以用线程池优化，
    // 1、如当线程池中的工作人员没有分配完，就继续将任务分配给线程池中空闲的工作人员
    MaterialWorker materialWorker = findAvailablePeopleToAssignTasks(true);
    materialWorker.developWorkPlan(task);

  }

  /**
   * 寻找空闲人员,即最早完成任务的人员
   * @param isFirst  true 则返回第一个空闲人员,false 则返回最晚完成任务的人员
   * @return
   */
  private MaterialWorker findAvailablePeopleToAssignTasks(boolean isFirst){

    MaterialWorker materialWorkerTmp = null;

    for (MaterialWorker materialWorker : materialWorkerSet){
      if(materialWorkerTmp == null ){
        materialWorkerTmp = materialWorker;
        continue;
      }

      //最晚完成任务的人员
      if(!isFirst && materialWorker.getTheLastTimeToComplete().isAfter(materialWorkerTmp.getTheLastTimeToComplete())){
        materialWorkerTmp = materialWorker;
      }

      //第一个空闲人员
      if(isFirst && materialWorker.getTheLastTimeToComplete().isBefore(materialWorkerTmp.getTheLastTimeToComplete())){
        materialWorkerTmp = materialWorker;
      }

    }

    return materialWorkerTmp;
  }

  /**
   * 创建任务ID
   * @return
   */
  private String createTaskId() {
    return  UUID.randomUUID().toString();
  }

}
